<template>
  <div class="api-example">
    <h2>API 使用示例</h2>
    
    <!-- 1. 显示加载状态 -->
    <div v-loading="loading" class="content">
      
      <!-- 2. 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="店铺名称">
          <el-input v-model="searchForm.name" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="营业中" value="营业中" />
            <el-option label="暂停营业" value="暂停营业" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 3. 数据表格 -->
      <el-table :data="shopList" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="店铺名称" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 4. 分页组件 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 5. 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑店铺" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="店铺名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editForm.address" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="营业中" value="营业中" />
            <el-option label="暂停营业" value="暂停营业" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getFoodStorePage, 
  getFoodStoreDetails, 
  updateFoodStoreById, 
  deleteFoodStoreById 
} from '@/api/shop'

// ==================== 1. 响应式数据定义 ====================
const loading = ref(false)
const saveLoading = ref(false)
const dialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 店铺列表
const shopList = ref([])

// 编辑表单
const editForm = reactive({
  id: null,
  name: '',
  address: '',
  phone: '',
  status: ''
})

// ==================== 2. API 调用函数 ====================

/**
 * 获取店铺列表 - 演示 GET/POST 请求
 */
const getShopList = async () => {
  loading.value = true
  try {
    // 准备请求参数
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      name: searchForm.name,
      status: searchForm.status
    }

    console.log('发送请求参数:', params)

    // 调用API
    const result = await getFoodStorePage(params)
    
    console.log('接收到响应:', result)

    // 处理响应数据
    shopList.value = result.records || []
    pagination.total = result.total || 0
    
    ElMessage.success('数据加载成功')
  } catch (error) {
    console.error('获取店铺列表失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取店铺详情 - 演示带参数的 GET 请求
 */
const getShopDetail = async (shopId) => {
  try {
    console.log('获取店铺详情, ID:', shopId)
    
    const result = await getFoodStoreDetails(shopId)
    
    console.log('店铺详情:', result)
    
    return result
  } catch (error) {
    console.error('获取店铺详情失败:', error)
    ElMessage.error('获取详情失败')
    throw error
  }
}

/**
 * 更新店铺信息 - 演示 PUT 请求
 */
const updateShop = async (shopId, shopData) => {
  try {
    console.log('更新店铺信息:', { shopId, shopData })
    
    const result = await updateFoodStoreById(shopId, shopData)
    
    console.log('更新结果:', result)
    
    ElMessage.success('更新成功')
    return result
  } catch (error) {
    console.error('更新店铺失败:', error)
    ElMessage.error('更新失败')
    throw error
  }
}

/**
 * 删除店铺 - 演示 DELETE 请求
 */
const deleteShop = async (shopId) => {
  try {
    console.log('删除店铺, ID:', shopId)
    
    const result = await deleteFoodStoreById(shopId)
    
    console.log('删除结果:', result)
    
    ElMessage.success('删除成功')
    return result
  } catch (error) {
    console.error('删除店铺失败:', error)
    ElMessage.error('删除失败')
    throw error
  }
}

// ==================== 3. 事件处理函数 ====================

/**
 * 搜索处理
 */
const handleSearch = () => {
  console.log('执行搜索:', searchForm)
  pagination.current = 1 // 重置到第一页
  getShopList()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  console.log('重置搜索条件')
  searchForm.name = ''
  searchForm.status = ''
  pagination.current = 1
  getShopList()
}

/**
 * 查看店铺详情
 */
const handleView = async (shop) => {
  console.log('查看店铺:', shop)
  try {
    const detail = await getShopDetail(shop.id)
    // 这里可以显示详情对话框或跳转到详情页
    console.log('店铺详细信息:', detail)
  } catch (error) {
    // 错误已在 getShopDetail 中处理
  }
}

/**
 * 编辑店铺
 */
const handleEdit = async (shop) => {
  console.log('编辑店铺:', shop)
  try {
    // 获取最新的店铺信息
    const detail = await getShopDetail(shop.id)
    
    // 填充编辑表单
    Object.assign(editForm, detail)
    
    // 显示编辑对话框
    dialogVisible.value = true
  } catch (error) {
    // 错误已在 getShopDetail 中处理
  }
}

/**
 * 删除店铺
 */
const handleDelete = async (shop) => {
  console.log('删除店铺:', shop)
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺 "${shop.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deleteShop(shop.id)
    
    // 重新加载列表
    getShopList()
  } catch (error) {
    if (error !== 'cancel') {
      // 错误已在 deleteShop 中处理
    }
  }
}

/**
 * 保存编辑
 */
const handleSave = async () => {
  console.log('保存店铺信息:', editForm)
  saveLoading.value = true
  try {
    await updateShop(editForm.id, {
      name: editForm.name,
      address: editForm.address,
      phone: editForm.phone,
      status: editForm.status
    })
    
    // 关闭对话框
    dialogVisible.value = false
    
    // 重新加载列表
    getShopList()
  } catch (error) {
    // 错误已在 updateShop 中处理
  } finally {
    saveLoading.value = false
  }
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size) => {
  console.log('分页大小改变:', size)
  pagination.size = size
  pagination.current = 1
  getShopList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current) => {
  console.log('当前页改变:', current)
  pagination.current = current
  getShopList()
}

// ==================== 4. 辅助函数 ====================

/**
 * 获取状态标签类型
 */
const getStatusType = (status) => {
  const typeMap = {
    '营业中': 'success',
    '暂停营业': 'danger',
    '待审核': 'warning'
  }
  return typeMap[status] || 'info'
}

// ==================== 5. 生命周期 ====================

/**
 * 组件挂载后自动加载数据
 */
onMounted(() => {
  console.log('组件挂载，开始加载数据')
  getShopList()
})
</script>

<style scoped>
.api-example {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.content {
  min-height: 400px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>